<html>
  <head>
    <title>Test HMAC</title>
    <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
	<script type="text/javascript" src="js/ejUtil.js"> </script>
	<script type="text/javascript" src="js/sjcl.js"></script>

	<!-- This javascript tests if hmac with sha256 functions as expected-->
	<script type="text/javascript">
		var testmsg = "The quick brown fox jumps over the lazy dog";
		var password = "key";
		
		document.write("Message is: " + testmsg);
		
		document.write("<br> <br>");
		document.write("Key used  : " + password);
		
		/* A good HMAC uses the format, for k key and x message:
		     HMAC(k, x) = SHA( [key1] || [SHA(key2 || x)] )
		
		   The idea is that a key1 and key2 used with sufficiently large hamming distance
		   from each other grants security, as far as we know today.
		   
		   See p143 of Stinson and http://en.wikipedia.org/wiki/HMAC#Examples_of_HMAC_.28MD5.2C_SHA1.2C_SHA256_.29
		   for details of why.
		*/
		
		
		
		//HMAC returned is an object, whose str representation is an array of integers
		var hmac = ejUtil.generate_hmac(password, testmsg);
		
		document.write("<br> <br>");
		document.write("HMAC is: " + hmac);
		
		var plaintext = testmsg + " " + hmac;
		
		document.write("<br> <br>");
		document.write("Plaintext is: " + plaintext);
		
		var ciphertext = ejUtil.aes_encrypt(password, plaintext);
		
		//Note: We added an id number at the beginning of every ciphertext for debugging so before decryption,
		//      need to remove it.
		encryptid = ciphertext.substring(0,1);
		ciphertext = ciphertext.substring(1, ciphertext.length);
		
		document.write("<br> <br>");
		document.write("Ciphertext is: " + ciphertext);
		
		var decryptedmsg = ejUtil.aes_decrypt(password, ciphertext);
		
		document.write("<br> <br>");
		document.write("Decrypted ciphertext is: " + decryptedmsg);
		
		var str_array = decryptedmsg.split(" ");
		
		document.write("<br> <br>");
		document.write("Encrypt id is : " + encryptid);
		
		document.write("<br> <br>");
		document.write("Extra Hash is: " + str_array.pop());
		
		document.write("<br> <br>");
		document.write("Decrypted HMAC is: " + str_array.pop());
		
		var dmsg = str_array.join(" ");
		
		document.write("<br> <br>");
		document.write("Decrypted Message is " + dmsg);
		
		//Sanity check that discovered I forgot foostring.join() joins with ',' by default when I needed ' ', a space.
		if(dmsg == testmsg){	
			document.write("<br> <br>");
			document.write("Messages match.");
		}
		else{
			document.write("<br> <br>");
			document.write("Messages do NOT match!");
		}
		
		var newhmac = ejUtil.generate_hmac(password, dmsg);
		
		document.write("<br> <br>");
		document.write("Recalculated HMAC is: " + newhmac);
		
		
		
	</script>
  </head>
  <body>
  </body>
</html>

